class Main extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            list: [],
            name: '',
            imgsrc: "",
            id: 0,
            imgsrc: "",
            orders: 1,
            isindex: "0",
            isclass: "0",
        };
    }

    formatlist(list) {
        var listitem = [], wulist = [];
        if (list.length > 0) {
            list.forEach((x, i) => {
                listitem.push(
                    <tr key={i}>
                        <td>{x.name}</td>
                        <td><antd.Switch style={{ marginRight: "15px" }} defaultChecked onChange={this.changestate.bind(this, x.id)} checked={x.state == 'ON' ? true : false} />{x.state == 'ON' ? '显示' : '隐藏'}</td>

                        <td style={{ width: '60px', cursor: "pointer" }} onClick={this.toorder.bind(this, x.id)} >{x.orders}</td>
                        <td className="">
                            <div className='operatebox'>
                                <div>
                                    {/* <img src="./src/edit.png" /> */}
                                    <p data-toggle="modal" data-target="#modalOne" className='edit' onClick={this.todetail.bind(this, x.id)}>编辑</p>
                                </div>
                                <div>
                                    {/* <img src="./src/del.png" /> */}
                                    <p className='edit red' onClick={this.del.bind(this, x.id)}>删除</p>
                                </div>


                            </div>
                        </td>
                    </tr>
                )
            });
        } else {
            wulist.push(
                <p className="wulist">暂无数据</p>
            )
        }
        this.setState({ listitem, list, originallist: list, wulist })
    }

    tosubtype(e) {
        window.location.href = "./goodssubtype.html?id=" + e;

    }

    // 编辑
    todetail(e) {
        var { list } = this.state;
        list.forEach(x => {
            if (x.id == e) {
                this.setState({ id: e, name: x.name,  orders: x.orders })
            }
        });
    }
    setisindex(e) {
        this.setState({ showloading: 'ON' })
        setindexGoodsType(e, res => {
            if (res.issuccess == 1) {
                alert("修改成功")
                this.freshlist()
            } else {
                this.setState({ showloading: '' })
                alert("修改失败")
            }
        })
    }
    setisclass(e) {
        this.setState({ showloading: 'ON' })
        setclassGoodsType(e, res => {
            if (res.issuccess == 1) {
                alert("修改成功")
                this.freshlist()
            } else {
                this.setState({ showloading: '' })
                alert("修改失败")
            }
        })
    }
    // 排序
    toorder(id) {
        let orders = prompt("请输入1-999的正整数，数字越大，排序越前")
        if (orders == "" || orders == null) {
            return;
        }
        if (isNaN(orders) || orders < 1 || orders > 999) {
            return;
        }
        orders = Math.floor(orders);
        setTypesorders({ id, orders }, res => {
            if (res.issuccess == 1) {
                alert("设置成功");
                // this.flist(res.list);
                this.freshlist();
            }
        });
    }
    // 删除
    del(e) {
        this.setState({ delid: e }, () => {
            $('#myModal').modal('toggle');
        })
    }
    confirmdel() {
        this.setState({ showloading: 'ON' })
        let { delid } = this.state
        delType(delid, res => {
            if (res.issuccess == 1) {
                this.setState({ showloading: '' })
                alert('删除成功')
                $('#myModal').modal('toggle');
                this.freshlist()
            } else {
                $('#myModal').modal('toggle');
                alert(res.msg);
            }
        })
    }

    submit() {
        var { name, orders } = this.state, that = this, err = '', imgarr = [];
        if (name == "") err = "请输入名称"
        if (err.length > 0) {
            alert(err);
            return
        }
        // this.setState({ showloading: 'ON' }, () => {
        //     imgarr = imgarr.concat(imgsrc)
        //     that.uploadimg(imgarr)
        // })

        this.setState({ showloading: 'ON' })
        var data = { name, orders }
        if (this.state.id > 0) data['id'] = this.state.id;
        addGoodsType(data, res => {
            if (res.issuccess == 1) {
                that.setState({ id: 0, name: '', orders: 1 }, () => {
                    $('#buttondismiss').click();
                    alert(`${this.state.id > 0 ? '修改' : '保存'}成功`);
                    that.freshlist()
                })

            }
        })

    }

    componentDidMount() {
        this.setState({ showloading: '' })
        let { isclass, isindex } = this.state
        $(`input[name=isindex][value=${isindex}]`).prop("checked", "checked");
        $(`input[name=isclass][value=${isclass}]`).prop("checked", "checked");

        // this.setState({showloading:'ON'})
        this.freshlist()

    }
    freshlist() {
        GoodsTypegetlist(res => {
            this.setState({ showloading: '' })
            if (res.issuccess == 1) {
                this.formatlist(res.list);
            }
        })

    }
    inputchange(prop, e) {
        this.setState({ [prop]: e.target.value })
    }

    add() {
        let isindex = "0", isclass = "0"
        $(`input[name=isindex][value=${isindex}]`).prop("checked", "checked");
        $(`input[name=isclass][value=${isclass}]`).prop("checked", "checked");
        this.setState({ id: 0, name: '', orders: "", isclass, isindex, imgsrc: "" }, () => {
            $('#modalOne').modal('toggle');
        })
    }

    // 图片
    filechangeimg(e) {
        var that = this;
        var filedata = $('#file' + e)[0].files[0];
        let _name, _fileName, filedatasize = 2048;

        _name = $('#file' + e)[0].value;
        _fileName = _name.substring(_name.lastIndexOf(".") + 1).toLowerCase();
        if (_fileName !== "png" && _fileName !== "jpg" && _fileName !== "gif" && _fileName !== "jpeg") {
            alert("上传图片格式不正确，请重新上传");
        } else {
            if (filedatasize < filedata.size / 1024) {
                alert("上传图片不能大于2M");
                return;
            }
            let filee = e
            var reader = new FileReader();
            reader.readAsDataURL(filedata);
            reader.onload = function (e) {
                var base64str = e.target.result;
                that.putswiperimglistdata([base64str], filee)
            }
        }
    }
    putswiperimglistdata(target, prop) {
        let imgsrc = '', that = this;
        imgsrc = target[0]
        if (!isBase64(imgsrc)) {
            if (imgsrc.indexOf(`${API_HEAD}`) == -1) {
                imgsrc = `${API_HEAD}imgs/${imgsrc}`

            }
        }
        that.setState({ [prop]: imgsrc })

    }
    clickupload(e) {
        $('#file' + e).click();
    }

    del_img(prop) {
        this.setState({ [prop]: '' })

    }
    changestate(i, e) {
        console.log(e, 'eeee', i, 'iddd');
        Typessetstate(i, res => {
            if (res.issuccess == 1) {
                this.freshlist()
                alert("设置成功")
            } else {
                this.setState({ showloading: '' })
                alert(res.msg)
            }
        })
    }
    // 上传图片
    uploadimg(arr) {
        let uploadimgarr = [],
            { name, imgsrc, orders, isindex, isclass } = this.state, that = this;
        arr.forEach((x, i) => {
            if (x.indexOf(`${API_HEAD}`) == -1) {
                if (isBase64(x)) {
                    uploadimg(x, res => {
                        if (res.issuccess == 1) {
                            x = `${API_HEAD}imgs/${res.path}`
                            uploadimgarr.push(x)
                        } else {
                            this.setState({ showloading: '' })
                            alert(res.msg)
                            err = 1
                            return;
                        }
                    })
                }
            } else {
                uploadimgarr.push(x)
            }
        })
        if (uploadimgarr.length == arr.length) {
            uploadimgarr.forEach((x, i) => {
                if (i == 0) {
                    imgsrc = x.replace(`${API_HEAD}imgs/`, '')
                }
                //  else {
                //     let lb = x.replace(`${API_HEAD}imgs/`, '')
                //     lbimgarr.push(lb)
                // }
            })

            var data = { name, imgsrc, orders, isindex, isclass };
            if (this.state.id > 0) data['id'] = this.state.id;
            console.log(data, 'data')
            addGoodsType(data, res => {
                this.setState({ showloading: '' })
                // this.setState({ isloading: !1 })
                if (res.issuccess == 1) {

                    alert(`${this.state.id > 0 ? '修改' : '保存'}成功`);
                    // window.location.href = "./dynamic.html";
                    isindex = "0", isclass = "0"
                    $(`input[name=isindex][value=${isindex}]`).prop("checked", "checked");
                    $(`input[name=isclass][value=${isclass}]`).prop("checked", "checked");
                    that.setState({ id: 0, name: '', orders: "", isclass, isindex, imgsrc: "" }, () => {
                        $('#buttondismiss').click();
                    })
                    that.freshlist()

                } else {
                    alert(res.msg)
                }
            })

        } else {
            alert('图片上传失败')
        }

    }


    render() {
        let { listitem, name, imgsrc, orders } = this.state;

        return (
            <div className="breadLinebox">
                <Modal content='确定要删除吗？' click={this.confirmdel.bind(this)} />
                <Loading hidden={this.state.showloading != 'ON'} />
                <div className="modal fade" id="modalOne" >


                    <div className="modal-dialog">
                        <div className="modal-content">

                            <div className="modal-header border">
                                <p className="modal-title">{this.state.id > 0 ? "编辑" : "新建"}</p>
                                <img data-dismiss="modal" src="./src/close.png" />
                            </div>
                            <div className="modal-body">
                                <div className="input-group">
                                    <span className="input-group-addon">名称</span>
                                    <input id='name' onChange={this.inputchange.bind(this, 'name')} value={name} type="text" placeholder='请输入名称' className="input" />
                                </div>
                                <div className="input-group">
                                    <span className="input-group-addon">排序</span>
                                    <input id='name' onChange={this.inputchange.bind(this, 'orders')} value={orders} type="text" placeholder='请输入1-999的正整数' className="input" />
                                </div>
                            </div>
                            <div className="modal-footer border">
                                <button type="button" className="closemod" data-dismiss="modal">关闭</button>
                                {/* <button type="button" onClick={this.submit.bind(this)} data-dismiss="modal" className="submitmod">提交</button> */}
                                <button type="button" onClick={this.submit.bind(this)} className="submitmod">提交</button>
                                <button type="button" id='buttondismiss' data-dismiss="modal" style={{ display: "none" }}></button>
                            </div>

                        </div>
                    </div>
                </div>
                <div className='content_wrap panel-default content_wrap'>
                    <div className="breadLine">
                        <div className="flexitems">
                            <div className="img">
                                {/* <img src='./src/lm_order1.png' /> */}
                                商品分类管理
                            </div>
                            <div className="tabletit">
                                <p className="add" data-toggle="modal" data-target="#modalOne" onClick={this.add.bind(this)}>新建</p>
                            </div>
                        </div>
                    </div>
                    <div className="contentBox">
                        <table className="tab">
                            <thead>
                                <tr>
                                    <th>名称</th>
                                    <th>是否显示</th>
                                    <th>排序</th>
                                    <th className="cz tconter">操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                {listitem}
                            </tbody>
                        </table>
                        {this.state.wulist}
                    </div>
                </div>
            </div>


        )


    }
}





ReactDOM.render(
    <div>
        <TopLine />
        <div id='body'>
            <LeftMenu code='goodstype' height='goods' />
            <Main />
        </div>
    </div>
    // <Barrage/>
    , $('.container')[0]
)